/*
 * dns.cpp
 *
 *  Created on: Dec 25, 2013
 *      Author: killerg
 */

#include "dns.h"

void dns_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
    dns_t::pend_t* pend = (dns_t::pend_t*)arg;
    if (!pend->cb) {
        delete pend;
        return;
    }

    int32_t addr = *(int32_t*)addresses;
    char buffer[INET_ADDRSTRLEN];
    pend->cb(pend->host, evutil_inet_ntop(AF_INET, &addr, buffer, INET_ADDRSTRLEN));
}

bool dns_t::init() {
    base = event_base_new();
    dns_base = evdns_base_new(base, 1);
    evdns_base_resolv_conf_parse(dns_base, DNS_OPTION_NAMESERVERS|DNS_OPTION_MISC|DNS_OPTION_HOSTSFILE, "/etc/resolv.conf");

    return true;
}

void dns_t::destroy() {
    evdns_base_free(dns_base, 1);
    event_base_free(base);
}

void dns_t::update() {
    event_base_loop(base, EVLOOP_NONBLOCK);
}

bool dns_t::query_ip(const char* host, result_cb_t cb) {
    auto pend = new pend_t;
    pend->cb = cb;
    pend->host = host;
    pend->dns = this;


    pend->req = evdns_base_resolve_ipv4(dns_base, host, 0, dns_callback, pend);
    if (NULL == pend->req) {
        delete pend;
        return false;
    }

    return true;
}
